<template>
  <div class="app-container">
    <el-form :model="memberForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="memberForm.mobile" style="width: 200px;"></el-input>
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="memberForm.nickname" style="width: 200px;"></el-input>
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <!--<el-radio-group v-model="memberForm.sex" clearable>
          <el-radio :value="2" label="男"></el-radio>
          <el-radio :value="1" label="女"></el-radio>
        </el-radio-group>-->
        <el-select v-model="memberForm.sex" clearable placeholder="请选择">
          <el-option :value="2" label="男"/>
          <el-option :value="1" label="女"/>
        </el-select>
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="memberForm.age" controls-position="right" :min="0"/>
      </el-form-item>

      <el-form-item label="用户头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="BASE_API+'/oss/file/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="memberForm.avatar" :src="memberForm.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import member from "@/api/member";

  export default {
    data() {
      return {
        imagecropperShow: false,//上传图片弹框是否显示
        imagecropperKey: 0,//上传头像标示值
        BASE_API: process.env.BASE_API,//后端访问地址
        saveBtnDisabled: false,//保存按钮是否禁用
        memberForm: {
          mobile: '',//手机号
          nickname: '',//昵称
          sex: '',//性别
          age: '',//年龄
          avatar: '',//头像
        },
        rules: {
          mobile: [//手机号正则表达式：/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {len: 11, message: '请输入11位的手机号码', trigger: 'blur'},
            {
              pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
              message: '请输入正确的手机号码'
            }
          ],
          nickname: [
            {required: true, message: '请输入昵称', trigger: 'blur'},
            {min: 2, max: 8, message: '昵称长度为2-8位', trigger: 'blur'},
          ],
          age: [//年龄正则表达式：/^(?:[1-9][0-9]?|1[01][0-9]|120)$/;//年龄是1-120之间有效
            {required: true, message: '请输入年龄', trigger: 'blur'},
            {pattern: /^(?:[1-9][0-9]?|1[01][0-9]|120)$/, message: '年龄在1-120之间', trigger: 'blur'},
          ],
          sex: [
            {required: true, message: '请选择性别', trigger: 'change'}
          ],
          avatar: [
            {required: true, message: '请上传头像', trigger: 'blur'}
          ],

        }
      };
    },
    created() {
      this.init()
    },
    watch: {
      $route(to, from) {
        this.init()
      }
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //判断是添加还是修改
            if (this.memberForm.id) {
              this.update()
            } else {
              this.save()
            }
            // console.log("============", this.memberForm.sex)
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //初始化
      init() {
        //判断路径中是否有id，如果有，获取id
        if (this.$route.params && this.$route.params.id) {
          this.memberForm.id = this.$route.params.id
          // alert(this.memberForm.id)
          //调用方法查询
          this.getMember()
        } else {
          //清空表单
          this.memberForm = {}
        }
      },
      //根据id查询会员信息
      getMember() {
        member.getMemberById(this.memberForm.id)
          .then(response => {
            this.memberForm = response.data.member
          })
      },
      //上传头像成功
      handleAvatarSuccess(response, file) {
        this.memberForm.avatar = response.data.url
      },
      //上传头像之前
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //添加
      save() {
        member.saveMember(this.memberForm)
          .then(response => {
            //提示
            this.$message({
              type: 'success',
              message: response.message
            })
            //跳转到列表页面
            this.$router.push({path: '/member/list'})
          })
      },
      //修改
      update() {
        member.updateMember(this.memberForm)
          .then(response => {
            //提示
            this.$message({
              type: 'success',
              message: response.message
            })
            //跳转到列表页面
            this.$router.push({path: '/member/list'})
          })
      },
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
